<?php

namespace core;

use core\Router;
use core\Log;

class App
{
    public static $cfg;

    /**
     * 框架运行入口
     */
    public static function run()
    {
        $routerTable = Router::getRouterTable();

        $uri = $_SERVER['REQUEST_URI'];
        $uri = str_replace('/index.php', '', $uri);

        $expRes = explode('/', $uri);
        if (isset($expRes[1]) && $expRes[1] != '') {
            // 有1就一定有2和3，路由使用严格模式，不进行默认的猜测
            $module = $expRes[1];
            $controller = $expRes[2];
            $function = $expRes[3];

            $callStr = strtolower('/' . $module . '/' . $controller . '/' . $function);
            if (array_key_exists($callStr, $routerTable)) {
                $call = $routerTable[$callStr];
            } else {
                // TODO.. 后续可以替换为自定义的404页面
                http_response_code(404);
                die;
            }
        } else {
            $module = '';
            $controller = '';
            $function = '';

            // 未指定模块，调用“/”对应的路由
            $call = $routerTable['/'];
        }

        if ($call[2] != '*' && strtolower($_SERVER['REQUEST_METHOD']) != strtolower($call[2])) {
            return '请求方式不匹配，请检查URI的请求方式。。';
        }

        $callInfo = explode('\\', $call[1]);
        $functionName = array_pop($callInfo);
        $className = implode('\\', $callInfo);

        $class = new $className();
        $response = $class->$functionName();

        $logContent = '[' . date('Y-m-d H:i:s') . "] call function $className\\$functionName";
        Log::saveModuleLog($callInfo[count($callInfo) - 3], $callInfo[count($callInfo) - 1], $logContent);
    }
}
